package itheima.com.myreflect3;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
//      declaredConstructor.setAccessible(true); 调私有构造必须进行   设置无障碍调用
        //获取class对象
        //获取构造方法对象
        //利用newInstance 创建Student的对象
//declaredConstructor.newInstance("liuxing")  根据指定的构造方法创建对象

        //        method1();
//method2()

        //获取class对象
        Class clazz = Class.forName("itheima.com.myreflect3.Student");
        //获取构造方法对象
        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(true);
        //利用newInstance 创建Student的对象
        Student student = (Student) declaredConstructor.newInstance("liuxing");
        System.out.println(student);

    }

    private static void method2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class clazz = Class.forName("itheima.com.myreflect3.Student");
        Constructor constructor = clazz.getConstructor();
        Student student = (Student) constructor.newInstance();
        System.out.println(student);
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class clazz = Class.forName("itheima.com.myreflect3.Student");
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        Student student = (Student) constructor.newInstance("zhangsan", 25);
        System.out.println(student);
    }
}
